package com.crm.common.util;

import java.util.concurrent.*;

/**
 * @author yincuimei
 * @Date 2021/7/5 9:15
 */
public class ThreadPool {

    /**
     * 线程池维护线程的最少数量
     */
    private static final int CORE_POOL_SIZE = 30;
    /**
     * 线程池维护线程的最大数量
     */
    private static final int MAX_POOL_SIZE = 100;
    /**
     * 线程池维护线程所允许的空闲时间
     */
    private static final int KEEP_ALIVE_TIME = 10;
    /**
     * 线程队列中允许的最大待执行线程数
     */
    private static final int BLOCKING_QUEUE_SIZE = 10000;
    private static ExecutorService executorService = null;

    /**
     * 在线程池中运行Runnable类
     */
    public static void execute(Runnable runnable) {
        if(executorService == null){
            executorService = new ThreadPoolExecutor(CORE_POOL_SIZE,
                    MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.MINUTES,
                    new ArrayBlockingQueue<Runnable>(BLOCKING_QUEUE_SIZE),
                    new ThreadPoolExecutor.DiscardOldestPolicy());
        }
        executorService.execute(runnable);
    }

    /**
     * 销毁方法
     */
    public static void destroy() {
        if (executorService != null) {
            executorService.shutdownNow();
        }
    }
}
